<template>
  <div class="doc-list-page">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2 class="page-title">文档列表管理</h2>
      <div class="page-actions">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建文档
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true">
        <el-form-item label="文档标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入文档标题"
            clearable
          />
        </el-form-item>
        <el-form-item label="所属分类">
          <el-cascader
            v-model="searchForm.categoryId"
            :options="categoryOptions"
            :props="cascaderProps"
            clearable
            placeholder="请选择分类"
          />
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="searchForm.difficulty" clearable>
            <el-option label="全部" value="" />
            <el-option label="入门" value="beginner" />
            <el-option label="进阶" value="intermediate" />
            <el-option label="高级" value="advanced" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.isPublished" clearable>
            <el-option label="全部" value="" />
            <el-option label="已发布" :value="true" />
            <el-option label="未发布" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 文档表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="title" label="文档标题" min-width="200">
        <template #default="{ row }">
          <el-link type="primary" @click="handleView(row)">
            {{ row.title }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="分类" width="150">
        <template #default="{ row }">
          <el-tag v-if="row.category">
            {{ row.category.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="difficulty" label="难度" width="100">
        <template #default="{ row }">
          <el-tag :type="getDifficultyType(row.difficulty)">
            {{ getDifficultyText(row.difficulty) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="来源" width="120">
        <template #default="{ row }">
          <div v-if="row.source">
            <el-tag size="small">{{ row.source.name }}</el-tag>
          </div>
          <span v-else>原创</span>
        </template>
      </el-table-column>
      <el-table-column prop="viewCount" label="浏览" width="80" />
      <el-table-column label="状态" width="80">
        <template #default="{ row }">
          <el-switch
            v-model="row.isPublished"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="updatedAt" label="更新时间" width="160">
        <template #default="{ row }">
          {{ formatDate(row.updatedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)">查看</el-button>
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 批量操作 -->
    <div v-if="selectedRows.length > 0" class="batch-actions">
      <span>已选择 {{ selectedRows.length }} 项</span>
      <el-button @click="handleBatchPublish">批量发布</el-button>
      <el-button @click="handleBatchUnpublish">批量下架</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import { useDocsStore } from '@/stores/docs'
import type { DocLesson, DocCategory } from '@/types/docs'

const router = useRouter()
const docsStore = useDocsStore()

// 状态
const loading = ref(false)
const tableData = ref<DocLesson[]>([])
const selectedRows = ref<DocLesson[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 搜索表单
const searchForm = reactive({
  title: '',
  categoryId: undefined as number | undefined,
  difficulty: '',
  isPublished: ''
})

// 级联选择器配置
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: true,
  emitPath: false
}

// 分类选项
const categoryOptions = computed(() => {
  const buildOptions = (categories: DocCategory[]): any[] => {
    return categories.map(cat => ({
      id: cat.id,
      name: cat.name,
      children: cat.children ? buildOptions(cat.children) : undefined
    }))
  }
  return buildOptions(docsStore.categoryTree.filter(cat => cat.isDocCategory))
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    const result = await docsStore.fetchDocLessons(params)
    if (result) {
      tableData.value = result.data || []
      total.value = result.pagination?.total || 0
    }
  } catch (error) {
    ElMessage.error('加载文档列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  searchForm.categoryId = undefined
  searchForm.difficulty = ''
  searchForm.isPublished = ''
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  loadData()
}

// 创建文档
const handleCreate = () => {
  router.push('/admin/docs/create')
}

// 查看文档
const handleView = (row: DocLesson) => {
  router.push(`/docs/lesson/${row.slug || row.id}`)
}

// 编辑文档
const handleEdit = (row: DocLesson) => {
  router.push(`/admin/docs/${row.id}/edit`)
}

// 删除文档
const handleDelete = async (row: DocLesson) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文档"${row.title}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除API
    loading.value = true
    await docsStore.deleteDocLesson(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    // 用户取消或删除失败
  } finally {
    loading.value = false
  }
}

// 状态切换
const handleStatusChange = async (row: DocLesson) => {
  try {
    await docsStore.updateDocLesson(row.id, { isPublished: row.isPublished })
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.isPublished = !row.isPublished
    ElMessage.error('状态更新失败')
  }
}

// 选择变化
const handleSelectionChange = (rows: DocLesson[]) => {
  selectedRows.value = rows
}

// 批量发布
const handleBatchPublish = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要发布选中的 ${selectedRows.value.length} 篇文档吗？`,
      '批量发布',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 批量更新
    for (const doc of selectedRows.value) {
      await docsStore.updateDocLesson(doc.id, { isPublished: true })
    }
    
    ElMessage.success('批量发布成功')
    loadData()
  } catch (error) {
    // 用户取消
  }
}

// 批量下架
const handleBatchUnpublish = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要下架选中的 ${selectedRows.value.length} 篇文档吗？`,
      '批量下架',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 批量更新
    for (const doc of selectedRows.value) {
      await docsStore.updateDocLesson(doc.id, { isPublished: false })
    }
    
    ElMessage.success('批量下架成功')
    loadData()
  } catch (error) {
    // 用户取消
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 篇文档吗？此操作不可恢复！`,
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    // 批量删除
    for (const doc of selectedRows.value) {
      await docsStore.deleteDocLesson(doc.id)
    }
    
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    loadData()
  } catch (error) {
    // 用户取消
  }
}

// 分页变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 格式化日期
const formatDate = (date: string) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 获取难度类型
const getDifficultyType = (difficulty: string) => {
  const map: Record<string, string> = {
    beginner: 'success',
    intermediate: 'warning',
    advanced: 'danger'
  }
  return map[difficulty] || ''
}

// 获取难度文本
const getDifficultyText = (difficulty: string) => {
  const map: Record<string, string> = {
    beginner: '入门',
    intermediate: '进阶',
    advanced: '高级'
  }
  return map[difficulty] || ''
}

onMounted(async () => {
  // 先加载分类数据
  await docsStore.fetchDocCategories()
  // 再加载文档列表
  loadData()
})
</script>

<style scoped>
.doc-list-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin: 0;
}

.page-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.batch-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: #fff;
  padding: 12px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 12px;
  z-index: 100;
}
</style> 